/*******************************************************************************
 * @(#)LockTest.java 2021年05月03日 21:55
 * Copyright 2021 明医众禾科技（北京）有限责任公司. All rights reserved.
 *******************************************************************************/
package learn.juc.lock;

import java.util.concurrent.ConcurrentLinkedDeque;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <b>Application name：</b> LockTest.java <br>
 * <b>Application describing： </b> <br>
 * <b>Copyright：</b> Copyright &copy; 2021 明医众禾科技（北京）有限责任公司 版权所有。<br>
 * <b>Company：</b> 明医众禾科技（北京）有限责任公司 <br>
 * <b>@Date：</b> 2021年05月03日 21:55 <br>
 * <b>@author：</b> <a href="mailto:chensg@miyzh.com"> chensg </a> <br>
 * <b>@version：</b>V1.0.0 <br>
 */
public class LockTest {

    private final ReadWriteLock lock = new ReentrantReadWriteLock();

//    private ConcurrentLinkedQueue queue = new ConcurrentLinkedQueue();

    private ConcurrentLinkedDeque queue = new ConcurrentLinkedDeque();

    public void get(String key) {
        lock.readLock().lock();
        try {
            System.out.println("current key is:" + key);
            queue.remove(key);
            queue.add(key);
            return;
//            if (queue.remove(key)) {
//                queue.add(key);
//                return;
//            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        lock.writeLock().lock();
        try {
            System.out.println("try write key is:" + key);
            this.queue.offer(key);
//            queue.add(key);
            Thread.sleep(2000);
        } catch (Exception e) {
        } finally {
            lock.writeLock().unlock();
        }

    }


    public static void main(String[] args) {
        LockTest lockTest = new LockTest();
        for (int i = 0; i < 1000; i++) {
            String key = i + "";
            new Thread(() -> {
                lockTest.get("1");
            }).start();
        }
    }

}